﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Win32;

namespace PerformanceMonitorSwitch
{
	public static class Stats
	{
		public static void Enable()
		{
			using (var key = GetPerfStatKey())
			{
				SetPerfStatKey(key, true);
			}
		}

		public static void Disable()
		{
			using (var key = GetPerfStatKey())
			{
				SetPerfStatKey(key, false);
			}
		}

		private static void SetPerfStatKey(RegistryKey key, bool enable)
		{
			/*
			Registry Settings for Performance Monitoring
			HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETCompactFramework\PerfMonitor
			"Counters"=dword:00000002

			The meaning of the values for "Counters" is: 
			0 - Disable PerfMon 
			1 - Enable performance monitoring (collect the data and output at the end of the application run to \mscoree.stat) 
			*/
			if (enable)
				key.SetValue("Counters", (int)1);
			else
				key.SetValue("Counters", (int)0);
		}

		private static RegistryKey GetPerfStatKey()
		{
			/*
			Registry Settings for Performance Monitoring
			HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETCompactFramework\PerfMonitor
			"Counters"=dword:00000002
			*/

			RegistryKey msKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft");
			RegistryKey netcfKey = msKey.OpenSubKey(@".NETCompactFramework", true);
			if (netcfKey == null)
				netcfKey = msKey.CreateSubKey(".NETCompactFramework");

			RegistryKey pfKey = netcfKey.OpenSubKey("PerfMonitor", true);
			if (pfKey == null)
				pfKey = netcfKey.CreateSubKey("PerfMonitor");


			netcfKey.Close();
			msKey.Close();

			return pfKey;
		}
	}
}
